package com.example.demo.controller;

import com.example.demo.common.AppVariable;
import com.example.demo.common.PasswordUtils;
import com.example.demo.common.ResultAjax;
import com.example.demo.model.Userinfo;
import com.example.demo.model.vo.UserinfoVO;
import com.example.demo.service.UserService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WHY
 * Date: 2023-09-16
 * Time: 18:59
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
@RequestMapping("/reg")
    public ResultAjax reg(Userinfo userinfo){
    //1.校验参数
        if(userinfo==null||!StringUtils.hasLength(userinfo.getUsername())
                ||!StringUtils.hasLength(userinfo.getPassword())){
            //参数异常
            return ResultAjax.fail(-1,"非法参数");
        }
        //密码加盐处理
        userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));

    //2.请求service进行添加操作(加到客户端)
    int ret=userService.reg(userinfo);
        //3.将执行的结果返回给前端
    return ResultAjax.success(ret);


    }
    @RequestMapping("login")
    public ResultAjax login(UserinfoVO userinfoVO, HttpServletRequest request){
        //1.参数校验
        if(userinfoVO== null && !StringUtils.hasLength(userinfoVO.getUsername()) ||
                !StringUtils.hasLength(userinfoVO.getPassword())){
            //非法登录
            return ResultAjax.fail(-1,"非法参数!");

        }
        //2.根据用户名查询对象(userinfo对象是数据库中的)(userinfoVo是前端传递过来的)
        Userinfo userinfo=userService.getUserByName(userinfoVO.getUsername());
        if(userinfo==null||userinfo.getId()==0){
            //不存在此用户名
            return ResultAjax.fail(-2,"用户名或者密码错误!");
        }

        //3.使用用户传递过来的密码和数据库中的密码进行比较
        //加盐解密
        if(!PasswordUtils.decrypt(userinfoVO.getPassword(),userinfo.getPassword())){
            //密码错误
            return ResultAjax.fail(-2,"用户名或者密码错误!");
        }

        //4.比较成功以后,将对象存储到session中
        HttpSession session=request.getSession();
        session.setAttribute(AppVariable.SESSION_USERINFO_KEY,userinfo);
        //5.将结果返回给用户
                return ResultAjax.success(1);



    }
    @RequestMapping("/logout")
    public ResultAjax logout(HttpServletRequest request){
    HttpSession session=request.getSession(false);
    if(session!=null&&session.getAttribute(AppVariable.SESSION_USERINFO_KEY)!=null){
        session.removeAttribute(AppVariable.SESSION_USERINFO_KEY);
    }
    return ResultAjax.success(1);
    }




}
